<?php

/**
 *
 * BEGIN UserAdmin.php
 *
 *
 *
 * @file UserAdmin.phpp
 * @brief This class provides data access methods for fan and commentator tables
 * @author Thato Selebogo, Wits University
 * @Copyright: © Wits University 2011 - All Rights Reserved
 * @License: BSD License (http://www.linfo.org/bsdlicense.html)
 *
 *
 * BEGIN CHANGELOG
 * Developers working on thee files are REQUIRED to maintain this CHANGELOG.
 * Please ensure you follow the Changelog Guidelines: http://code.google.com/p/dazzler/wiki/DazzlerDevelopGuideline?ts=1315476570&updated=DazzlerDevelopGuideline
 * !==================================================================================================================================================================
 *
 * VERSION 1.0.0
 * 	+ File Created, Thato Selebogo, 19 September 2011
 *
 * VERSION 1.0.1
 * 	- Moved the functionality to connect to database to the base class, Thato Selebogo, 19 September 2011
 *
 * VERSION 1.1.1
 * 	- Moved the logic to handle sessions to UserLogic, Thato Selebogo, 11 October 2011
 *
 * ================================================================================================================================================================!
 * END CHANGELOG
 */
/* * *****************************************************************************************************************************************************************
 *
 * BEGIN Direct Call Check
 *
  /***************************************************************************************************************************************************************** */
class UserAdmin extends baseClass {

    /**
     * Holds the database adapter singleton instance
     *
     * @var    DatabaseAdapterInterface
     * @access protected
     */

    protected $_databaseAdapter;

    /**
     * Holds the database table being processed
     *
     * @var    String
     * @access protected
     */
    protected $_databaseTable;

    /**
     * Constructor
     *
     * @param  void
     * @return void
     */
    public function __construct() {

        // Get database adapter singleton from the base class
        $this->_databaseAdapter = parent::databaseAdapter();
        parent::parseLanguageErrorLogFile();
    }

    /**
     * Inserts fan information
     *
     * @param  string $firstName
     * @param  string $lastName
     * @param  string $username
     * @param  string $password
     * @param  string $nickName
     * @param  string $email
     *
     * @return int
     */

    public function registerFan($firstName, $lastName, $username, $password, $nickName, $email) {
        $userData = array(
            'USER_ID' => '',
            'USER_FNAME' => $firstName,
            'USER_LNAME' => $lastName,
            'USER_USERNAME' => $username,
            'USER_PASSWORD' => $password,
            'USER_EML' => $email,
            'USER_ADMIN_LVL' => '0');

        $errors = array();
        // make sure manditory fields have been entered
        if (empty($username)) {
            $exceptionMessage = $this->lang_ini_array['ERRORS']['BlankUsernameError'];
            throw new Exception($exceptionMessage);
        }


        /**
         * @todo move to presenter
         *
         */
        if (!($this->isUsernameAvailable($username))) {
            throw new Exception($this->lang_ini_array['ERRORS']['UnavailableUsernameError']);
        }

        if (empty($password)) {
            throw new Exception($this->lang_ini_array['ERRORS']['BlankPasswordError']);
        }

        if (empty($firstName)) {
            throw new Exception($this->lang_ini_array['ERRORS']['BlankFirstNameError']);
        }

        if (empty($lastName)) {
            throw new Exception($this->lang_ini_array['ERRORS']['BlankLastNameError']);
        }

        if (empty($email)) {
            throw new Exception($this->lang_ini_array['ERRORS']['BlankEmailError']);
        }

        //Encrypt the password before storage
        $encryptPassword = md5($password);
        $userData['USER_PASSWORD'] = $encryptPassword;

        //Insert into USER table
        $this->_databaseTable = 'USER';
        $id = $this->_databaseAdapter->insert($this->_databaseTable, $userData);

        //Insert into FAN table
        $this->_databaseTable = 'FAN';
        $fanData = array(
            'FAN_ID' => '',
            'FAN_NNAME' => $nickName,
            'FAN_MESG' => '',
            'USER_USER_ID' => $id);
        $id = $this->_databaseAdapter->insert($this->_databaseTable, $fanData);
        return $id;
    }

    /**
     * Inserts commentator information
     *
     * @param  string $firstName
     * @param  string $lastName
     * @param  string $username
     * @param  string $password
     * @param  string $profile
     * @param  string $email
     *
     * @return int
     */
    public function registerCommntor($firstName, $lastName, $username, $password, $profile, $email) {

        $userData = array(
            'USER_ID' => '',
            'USER_FNAME' => $firstName,
            'USER_LNAME' => $lastName,
            'USER_USERNAME' => $username,
            'USER_PASSWORD' => $password,
            'USER_EML' => $email,
            'USER_ADMIN_LVL' => '1');

        $errors = array();
        // make sure manditory fields have been entered
        if (empty($username)) {
            $exceptionMessage = $this->lang_ini_array['ERRORS']['BlankUsernameError'];
            throw new Exception($exceptionMessage);
        }

        /**
         * @todo move to presenter
         *
         */
        if (!($this->isUsernameAvailable($username))) {
            throw new Exception($this->lang_ini_array['ERRORS']['UnavailableUsernameError']);
        }

        if (empty($password)) {
            throw new Exception($this->lang_ini_array['ERRORS']['BlankPasswordError']);
        }

        if (empty($firstName)) {
            throw new Exception($this->lang_ini_array['ERRORS']['BlankFirstNameError']);
        }

        if (empty($lastName)) {
            throw new Exception($this->lang_ini_array['ERRORS']['BlankLastNameError']);
        }

        if (empty($email)) {
            throw new Exception($this->lang_ini_array['ERRORS']['BlankEmailError']);
        }

        //Encrypt password
        $encryptPassword = md5($password);
        $userData['USER_PASSWORD'] = $encryptPassword;

        //Store info in the USER table
        $this->_databaseTable = 'USER';
        $id = $this->_databaseAdapter->insert($this->_databaseTable, $userData);

        //Store info in the COMMENTATOR table
        $this->_databaseTable = 'COMMENTATOR';
        $commentatorData = array(
            'COMMENTATOR_ID' => '',
            'COMMENTATOR_PROFL' => $profile,
            'USER_USER_ID' => $id);
        $id = $this->_databaseAdapter->insert($this->_databaseTable, $commentatorData);
        return $id;
    }

    /**
     * Allows a fan to select which game he/she wishes to comment on
     *
     * @param  int $fanId
     * @param  int $gameId
     *
     * @return int
     */
    public function populateFanHasGame($gameId, $fanId) {
        //Insert into the bridge entity.
        $this->_databaseTable = 'FAN_has_GAME';
        $data = array(
            'FAN_FAN_ID' => $fanId,
            'GAME_GAME_ID' => $gameId);
        $id = $this->_databaseAdapter->insert($this->_databaseTable, $data);
        return $id;
    }

    /**
     * Allows a commentator to select which game he/she wishes to comment on
     *
     * @todo move the session stuff into model. Commentator Id should be an arguement
     *
     * @param  int $gameId
     *
     * @return int
     */
    public function isGameNotLocked($gameId) {

        //Confirm that game is not locked.
        $this->_databaseTable = 'COMMENTATOR_has_GAME';
        $query = "SELECT COUNT(*) AS count FROM $this->_databaseTable WHERE GAME_GAME_ID = '$gameId'";
        $this->_databaseAdapter->query($query);
        $result = $this->_databaseAdapter->fetch();
        if (($result['count']) == 0) {
            
            return true;
        } else {
            return false;
        }
    }

    public function populateCommentatorHasGame($gameId, $commentatorId)
    {
        //Insert into the bridge entity.
            $data = array(
                'COMMENTATOR_COMMENTATOR_ID' => $commentatorId,
                'GAME_GAME_ID' => $gameId);
            $id = $this->_databaseAdapter->insert('COMMENTATOR_has_GAME', $data);
    }


    /**
     * Allows a user to be authenticated
     *
     * @param  string $userName
     * @param  string $password
     *
     * @return bool
     */

    public function authenticateUser($userName, $password) {
        $this->_databaseTable = 'USER';

        //Encrypt the password
        $password = md5($password);

        $query = "SELECT COUNT(*) AS count FROM $this->_databaseTable WHERE USER_USERNAME = '$userName'AND USER_PASSWORD = '$password'";
        $this->_databaseAdapter->query($query);
        $result = $this->_databaseAdapter->fetch();
        if (($result['count']) == 1) {
            return true;
        } else {
            return false;
        }

    }


    public function logOn($username, $password) {
        if ($this->authenticateUser($username, $password)) {
            $password = md5($password);
            $this->_databaseTable = 'USER';
            $this->_databaseAdapter->select($this->_databaseTable, "USER_USERNAME='$username'");
            $resultArray = $this->_databaseAdapter->fetch();
            return $resultArray;
        }
    }

    /**
     * Checks if username has not been already used
     *
     * @param  string $userName
     *
     * @return bool
     */

    public function isUsernameAvailable($userName) {
        $this->_databaseTable = 'USER';
        $query = "SELECT COUNT(*) AS count FROM $this->_databaseTable WHERE USER_USERNAME = '$userName'";
        $this->_databaseAdapter->query($query);
        $result = $this->_databaseAdapter->fetch();
        if (($result['count']) == 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Checks if email has not been already used
     *
     * @param  string $email
     *
     * @return bool
     */

    public function isEmailAvailable($email) {
        $this->_databaseTable = 'USER';
        $query = "SELECT COUNT(*) AS count FROM $this->_databaseTable WHERE USER_EML = '$email'";
        $this->_databaseAdapter->query($query);
        $result = $this->_databaseAdapter->fetch();
        if (($result['count']) == 0) {
            return true;
        } else {
            return false;
        }
    }

    public function getFanDetails($userName) {
        $this->_databaseTable = 'FAN';
        $query = "SELECT u.USER_ID, USER_USERNAME, USER_FNAME, USER_LNAME, USER_EML, f.FAN_NNAME
                  FROM
                  USER u JOIN
                  FAN f ON u.USER_ID = f.USER_USER_ID
                  WHERE u.USER_USERNAME = '$userName'";
        $this->_databaseAdapter->query($query);
        $row = $this->_databaseAdapter->fetch();
        return $row;
    }

    public function getFanDetailsWithId($userId) {
        $this->_databaseTable = 'FAN';
        $query = "SELECT u.USER_ID, USER_USERNAME, USER_FNAME, USER_LNAME, USER_EML, f.FAN_NNAME, f.FAN_ID
                  FROM
                  USER u JOIN
                  FAN f ON u.USER_ID = f.USER_USER_ID
                  WHERE u.USER_ID = '$userId'";
        $this->_databaseAdapter->query($query);
        $row = $this->_databaseAdapter->fetch();
        return $row;
    }

    /* !
     * \brief get all commentators
     */

    public function getAllCommentators() {
        $this->_databaseTable = 'COMMENTATOR';
        $query = "SELECT *
                  FROM
                  USER u JOIN
                  COMMENTATOR c ON u.USER_ID = c.USER_USER_ID";
        $this->_databaseAdapter->query($query);
        $resultArray = array();
        while ($row = $this->_databaseAdapter->fetch()) {
            extract($row);
            $resultArray[] = $row;
        }
        return $resultArray;
    }

    public function getCommentatorDetails($userName) {
        $this->_databaseTable = 'COMMENTATOR';
        $query = "SELECT u.USER_ID, USER_USERNAME, USER_FNAME, USER_LNAME, USER_EML, c.COMMENTATOR_PROFL
                  FROM
                  USER u JOIN
                  COMMENTATOR c ON u.USER_ID = c.USER_USER_ID
                  WHERE u.USER_USERNAME = '$userName'";
        $this->_databaseAdapter->query($query);
        $row = $this->_databaseAdapter->fetch();
        extract($row);
        return $row;
        
    }

    public function getCommentatorDetailsWithId($userId) {
        $this->_databaseTable = 'COMMENTATOR';
        $query = "SELECT u.USER_ID, USER_USERNAME, USER_FNAME, USER_LNAME, USER_EML, USER_ADMN_LVL, c.COMMENTATOR_PROFL, c.COMMENTATOR_ID
                  FROM
                  USER u JOIN
                  COMMENTATOR c ON u.USER_ID = c.USER_USER_ID
                  WHERE u.USER_ID = '$userId'";
        $this->_databaseAdapter->query($query);
        $row = $this->_databaseAdapter->fetch();
        return $row;
    }

        public function getCommentatorDetailsWithCommentatorId($commentatorId) {
        $this->_databaseTable = 'COMMENTATOR';
        $query = "SELECT u.USER_FNAME, USER_LNAME, USER_EML, c.COMMENTATOR_PROFL
                  FROM
                  USER u JOIN
                  COMMENTATOR c ON u.USER_ID = c.USER_USER_ID
                  WHERE c.COMMENTATOR_ID = '$commentatorId'";
        $this->_databaseAdapter->query($query);
        $row = $this->_databaseAdapter->fetch();
        return $row;
    }

    public function updateFanDetails($id, $firstName, $lastName, $username, $nickName, $email) {

        // make sure manditory fields have been entered
        if (empty($username)) {
            $exceptionMessage = $this->lang_ini_array['ERRORS']['BlankUsernameError'];
            throw new Exception($exceptionMessage);
        }

        if (empty($firstName)) {
            throw new Exception($this->lang_ini_array['ERRORS']['BlankFirstNameError']);
        }

        if (empty($lastName)) {
            throw new Exception($this->lang_ini_array['ERRORS']['BlankLastNameError']);
        }

        if (empty($email)) {
            throw new Exception($this->lang_ini_array['ERRORS']['BlankEmailError']);
        }

        $this->_databaseTable = 'USER';
        $data = array(
            'USER_FNAME' => $firstName,
            'USER_LNAME' => $lastName,
            'USER_USERNAME' => $username,
            'USER_EML' => $email);

        $this->_databaseAdapter->update($this->_databaseTable, $data, "USER_ID=$id");

        //Update FAN table as well
        $this->_databaseTable = 'FAN';
        $data = array(
            'FAN_NNAME' => $nickName);

        return $this->_databaseAdapter->update($this->_databaseTable, $data, "USER_USER_ID=$id");
    }

    public function updateCommntorDetails($id, $firstName, $lastName, $username, $profile, $email) {
        $errors = array();
        // make sure manditory fields have been entered
        if (empty($username)) {
            $errors[] = 'Username cannot be blank.';
        }

        if (empty($firstName)) {
            $errors[] = 'First name cannot be blank.';
        }

        if (empty($lastName)) {
            $errors[] = 'Last name cannot be blank.';
        }

        if (empty($email)) {
            $errors[] = 'Email address cannot be blank.';
        }

        if (count($errors) > 0) {
            return $errors;
        }

        $this->_databaseTable = 'USER';
        $data = array(
            'USER_FNAME' => $firstName,
            'USER_LNAME' => $lastName,
            'USER_USERNAME' => $username,
            'USER_EML' => $email);

        $this->_databaseAdapter->update($this->_databaseTable, $data, "USER_ID=$id");


        $this->_databaseTable = 'COMMENTATOR';
        $data = array(
            'COMMENTATOR_PROFL' => $profile);

        return $this->_databaseAdapter->update($this->_databaseTable, $data, "USER_USER_ID=$id");
    }

    public function updateUserPasswd($id, $passWord) {
        $errors = array();
        // make sure manditory fields have been entered
        if (empty($passWord)) {
            $errors[] = 'Password cannot be blank.';
        }


        if (count($errors) > 0) {
            return $errors;
        }
        $passWord = md5($passWord);

        $this->_databaseTable = 'USER';
        $data = array(
            'USER_PASSWORD' => $passWord);

        return $this->_databaseAdapter->update($this->_databaseTable, $data, "USER_ID=$id");
    }

    public function insertFanMsg($id, $msg) {
        $errors = array();
        // make sure manditory fields have been entered
        if (empty($msg)) {
            $errors[] = 'Message cannot be blank.';
        }
        if (!(isset($_SESSION['logged']))) {
            $errors[] = 'Not logged on.';
        }



        if (count($errors) > 0) {
            return $errors;
        }

        $this->_databaseTable = 'FAN';
        $data = array(
            'FAN_MESG' => $msg);

        return $this->_databaseAdapter->update($this->_databaseTable, $data, "USER_USER_ID=$id");
    }

    public function deleteFan($userId, $username) {
        $query = "DELETE u, f, fg
                  FROM USER AS u
                  LEFT JOIN FAN AS f ON f.USER_USER_ID = u.USER_ID
                  LEFT JOIN FAN_has_GAME AS fg ON fg.FAN_FAN_ID = f.FAN_ID
                  WHERE u.USER_USERNAME='$username'AND u.USER_ID='$userId'";
        $this->_databaseAdapter->query($query);
        return $this->_databaseAdapter->getAffectedRows();
    }

    public function deleteCommentator($userId, $username) {
        $query = "DELETE u, c, cg
                  FROM USER AS u
                  LEFT JOIN COMMENTATOR AS c ON c.USER_USER_ID = u.USER_ID
                  LEFT JOIN COMMENTATOR_has_GAME AS cg ON cg.COMMENTATOR_COMMENTATOR_ID = c.COMMENTATOR_ID
                  WHERE u.USER_USERNAME='$username'AND u.USER_ID='$userId'";
        $this->_databaseAdapter->query($query);
        return $this->_databaseAdapter->getAffectedRows();
    }

    public function deleteCommentatorFromGame($commentatorId) {
                $this->_databaseTable = 'COMMENTATOR_has_GAME';
                $this->_databaseAdapter->delete($this->_databaseTable,"COMMENTATOR_COMMENTATOR_ID='$commentatorId'");
                
    }

    public function deleteFanFromGame($fanId) {
                $this->_databaseTable = 'FAN_has_GAME';
                $this->_databaseAdapter->delete($this->_databaseTable,"FAN_FAN_ID='$fanId'");

    }

}

/*
 *
 * END UserAdmin.php
 *
 */
?>
